import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @Classname CompareTest
 * @Description 比较器的使用
 * @Date 2023/2/2 23:18
 * @Created by louzhuangxi
 */
public class CompareTest {
    /**
     * Comparable的使用
     */
    @Test
    public void test01() {
        String[] arrays = new String[]{"1", "2", "5", "3"};
        Arrays.sort(arrays);
        System.out.println(Arrays.toString(arrays));

        Person[] persons = new Person[4];
        persons[0] = new Person("2张三", 20);
        persons[1] = new Person("1张三", 20);
        persons[2] = new Person("李四", 23);
        persons[3] = new Person("王武", 30);
        Arrays.sort(persons);
        System.out.println(Arrays.toString(persons));
    }

    /**
     * Comparator的使用
     */
    @Test
    public void test02() {
        String[] arrays = new String[]{"1", "2", "5", "3"};
        Arrays.sort(arrays, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return -o1.compareTo(o2);
            }
        });
        System.out.println(Arrays.toString(arrays));

        Person[] persons = new Person[4];
        persons[0] = new Person("2张三", 20);
        persons[1] = new Person("1张三", 20);
        persons[2] = new Person("李四", 23);
        persons[3] = new Person("王武", 30);
        Arrays.sort(persons, new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                if (o1.getAge() > o2.getAge()) {
                    return 1;
                } else if (o1.getAge() < o2.getAge()) {
                    return -1;
                } else {
                    return -o1.getName().compareTo(o2.getName());
                }
            }
        });
        System.out.println(Arrays.toString(persons));
    }
}

class Person implements Comparable {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Person{");
        sb.append("name='").append(name).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }

    @Override
    public int compareTo(Object o) {
        if (o instanceof Person) {
            Person person = (Person) o;
            if (this.getAge() > person.getAge()) {
                return 1;
            } else if (this.getAge() < person.getAge()) {
                return -1;
            } else {
                return this.name.compareTo(person.getName());
            }
        }
        return 0;
    }
}
